﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using System.Threading;
using System.Diagnostics;

namespace TranslatorCAO
{
    public partial class MainWnd : Form
    {
        public MainWnd()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }
        /// <summary>
        /// 开始翻译
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btn_trans_Click(object sender, EventArgs e)
        {
            String tlang = cbb_tlang.SelectedItem.ToString();
            int cnt = int.Parse(transcnt.Text.ToString());
            String temp = input.Text;
            cnt = cnt >= 30 ? 30 : cnt;
            await Task.Run(()=>
            {
                for (int i = 0; i < cnt; i++)
                {
                    tip.Text = "正在进行第" + (i + 1) + "次转换";
                    temp = translate(temp, "zh", tlang);
                    Thread.Sleep(2500);
                    temp = translate(temp, tlang, "zh");
                    Thread.Sleep(2500);
                }
            });
            
            output.Text = temp;
        }
        /// <summary>
        /// 计算MD5值
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string EncryptString(string str)
        {
            MD5 md5 = MD5.Create();
            // 将字符串转换成字节数组
            byte[] byteOld = Encoding.UTF8.GetBytes(str);
            // 调用加密方法
            byte[] byteNew = md5.ComputeHash(byteOld);
            // 将加密结果转换为字符串
            StringBuilder sb = new StringBuilder();
            foreach (byte b in byteNew)
            {
                // 将字节转换成16进制表示的字符串，
                sb.Append(b.ToString("x2"));
            }
            // 返回加密的字符串
            return sb.ToString();
        }
        public String translate(String text,String slang,String tlang)
        {
            // 原文
            string q = text;
            // 源语言
            string from = slang;
            // 目标语言
            string to = tlang;
            // 改成您的APP ID
            string appId = "20200401000409996";
            Random rd = new Random();
            string salt = rd.Next(100000).ToString();
            // 改成您的密钥
            string secretKey = "bXZltB2kl8vgRMWLfTTt";
            string sign = EncryptString(appId + q + salt + secretKey);
            string url = "http://api.fanyi.baidu.com/api/trans/vip/translate?";
            url += "q=" + HttpUtility.UrlEncode(q);
            url += "&from=" + from;
            url += "&to=" + to;
            url += "&appid=" + appId;
            url += "&salt=" + salt;
            url += "&sign=" + sign;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";
            request.UserAgent = null;
            request.Timeout = 6000;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            Trans trans = new Trans();
            trans = JsonConvert.DeserializeObject<Trans>(retString);
            string s = trans.trans_result[0].dst.ToString();
            for(int i = 1;i<trans.trans_result.Count;i++)
                s+=Environment.NewLine + trans.trans_result[i].dst.ToString();
            return s;
        }
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainWnd_Load(object sender, EventArgs e)
        {
            this.cbb_tlang.SelectedIndex = 0;
            this.cbb_fac.SelectedIndex = 0;
            this.transcnt.Text = "10";
        }
        /// <summary>
        /// 监控输入的值，防止产生错误
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void transcnt_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 13 && e.KeyChar != 46)
                    e.Handled = true;
        }

        /// <summary>
        /// 百度tts
        /// </summary>
        /// <param name="strFileName"></param>
        /// <param name="strTTS"></param>
        /// <returns></returns>
        public int Tts(string strFileName, string strTTS)
        {
            // 设置APPID/AK/SK
            var APP_ID = "19185603";
            var API_KEY = "pLzUTEErZoDRIaRi5PZaAVQy";
            var SECRET_KEY = "dyxSw6pVU2Yw6gPbsxCGt4CAULBj6UwQ";

            var client = new Baidu.Aip.Speech.Tts(API_KEY, SECRET_KEY);

            client.Timeout = 60000;  // 修改超时时间

            // 可选参数
            var option = new Dictionary<string, object>()
            {
                {"spd", 5}, // 语速
                {"vol", 9}, // 音量
                {"pit", 5}, // 音调
                {"per", 4}  // 发音人，4：情感度丫丫童声
 
            };

            var result = client.Synthesis(strTTS, option);

            if (result.ErrorCode == 0)
            {
                File.WriteAllBytes(strFileName, result.Data);
                return 1;
            }

            return 0;
        }
        /// <summary>
        /// 转语音
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btn_tovoice_Click(object sender, EventArgs e)
        {
            await Task.Run(() =>
            {
                Tts("result.mp3", output.Text.ToString());
            });
            if (File.Exists("result.mp3"))
            {
                ProcessStartInfo psi = new ProcessStartInfo("result.mp3");
                Process p = new Process();
                p.StartInfo = psi;
                p.Start();
            }
        }
    }
}
